<template>
  <el-dialog
      v-model="visible"
      title="案例编辑"
      width="600px"
      :close-on-click-modal="false"
      @close="handleClose"
  >
    <el-form
        ref="caseFormRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        size="default"
    >
      <!-- 案例标题 -->
      <el-form-item label="案例标题" prop="title">
        <el-input
            v-model="formData.title"
            placeholder="请输入案例标题"
            maxlength="100"
            show-word-limit
        ></el-input>
      </el-form-item>

      <!-- 缩略图上传 -->
      <el-form-item label="缩略图" prop="thumbnailUrl">
        <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            accept="image/*"
            :show-file-list="false"
        >
          <div v-if="formData.thumbnailUrl" class="uploaded-img">
            <el-image
                :src="formData.thumbnailUrl"
                fit="cover"
                style="width: 120px; height: 80px; border-radius: 4px;"
                :preview-src-list="[formData.thumbnailUrl]"
            ></el-image>
            <el-button
                size="mini"
                type="text"
                class="delete-img-btn"
                @click="handleDeleteImg"
            >
              删除
            </el-button>
          </div>
          <el-button v-else type="primary" icon="Upload">
            点击上传
          </el-button>
        </el-upload>
        <div class="form-hint">支持 JPG、PNG 格式，建议尺寸 300*200</div>
      </el-form-item>

      <!-- 工具使用 -->
      <el-form-item label="工具使用" prop="toolUsed">
        <el-input
            v-model="formData.toolUsed"
            placeholder="请输入使用的工具（如：Python、Excel）"
            maxlength="50"
            show-word-limit
        ></el-input>
      </el-form-item>

      <!-- 作者ID -->
      <el-form-item label="作者ID" prop="authorId">
        <el-input
            v-model="formData.authorId"
            placeholder="请输入作者ID"
            type="number"
        ></el-input>
      </el-form-item>

      <!-- 案例状态 -->
      <el-form-item label="发布状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择状态">
          <el-option label="草稿" value="draft"></el-option>
          <el-option label="已发布" value="published"></el-option>
        </el-select>
      </el-form-item>

      <!-- 案例内容 -->
      <el-form-item label="案例内容" prop="content">
        <el-input
            v-model="formData.content"
            placeholder="请输入案例详细内容"
            type="textarea"
            rows="6"
            maxlength="2000"
            show-word-limit
        ></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import { addCaseStudy, updateCaseStudy } from '@/api/caseStudies';

// 接收父组件传递的 props
const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false
  },
  caseStudy: {
    type: Object,
    default: () => null
  }
});

// 向父组件传递事件
const emit = defineEmits(['close', 'save']);

// 表单引用（用于校验）
const caseFormRef = ref(null);

// 上传相关配置
const uploadUrl = 'http://your-domain.com/api/upload/image'; // 替换为实际上传接口
const loading = ref(false);

// 表单数据
const formData = reactive({
  caseId: null,          // 案例ID（编辑时自动填充）
  title: '',             // 案例标题
  thumbnailUrl: '',      // 缩略图URL
  toolUsed: '',          // 工具使用
  authorId: null,        // 作者ID
  status: 'draft',       // 默认状态：草稿
  content: '',           // 案例内容
  createdAt: null,       // 创建时间（后端自动生成）
  viewsCount: 0,         // 浏览量（后端自动维护）
  likesCount: 0          // 点赞量（后端自动维护）
});

// 监听props.caseStudy变化，同步到表单数据
watch(
    () => props.caseStudy,
    (newVal) => {
      if (newVal) {
        // 编辑：将传入的案例数据复制到表单
        Object.assign(formData, newVal);
      } else {
        // 新增：重置表单
        resetFormData();
      }
    },
    { immediate: true } // 初始加载时执行
);

// 重置表单数据
const resetFormData = () => {
  formData.caseId = null;
  formData.title = '';
  formData.thumbnailUrl = '';
  formData.toolUsed = '';
  formData.authorId = null;
  formData.status = 'draft';
  formData.content = '';
  formData.createdAt = null;
  formData.viewsCount = 0;
  formData.likesCount = 0;
};

// 表单校验规则
const formRules = {
  title: [
    { required: true, message: '请输入案例标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2-100 个字符之间', trigger: 'blur' }
  ],
  toolUsed: [
    { required: true, message: '请输入工具使用信息', trigger: 'blur' },
    { max: 50, message: '工具使用信息不超过 50 个字符', trigger: 'blur' }
  ],
  authorId: [
    { required: true, message: '请输入作者ID', trigger: 'blur' },
    { type: 'number', message: '作者ID必须为数字', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择发布状态', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入案例内容', trigger: 'blur' },
    { min: 10, max: 2000, message: '内容长度在 10-2000 个字符之间', trigger: 'blur' }
  ]
};

// 图片上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片格式文件！');
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB！');
  }

  return isImage && isLt2M;
};

// 图片上传成功回调
const handleUploadSuccess = (response) => {
  // 假设上传接口返回 { code: 200, data: { url: 'xxx' } }
  if (response?.data?.url) {
    formData.thumbnailUrl = response.data.url;
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error('图片上传失败：返回格式错误');
  }
};

// 图片上传失败回调
const handleUploadError = () => {
  ElMessage.error('图片上传失败，请重试');
};

// 删除已上传的图片
const handleDeleteImg = () => {
  formData.thumbnailUrl = '';
};

// 关闭弹窗
const handleClose = () => {
  // 重置表单校验状态
  if (caseFormRef.value) {
    caseFormRef.value.clearValidate();
  }
  // 通知父组件关闭
  emit('close');
};

// 提交表单（新增/编辑）
const handleSubmit = async () => {
  // 表单校验
  try {
    await caseFormRef.value.validate();
  } catch (error) {
    ElMessage.warning('表单校验失败，请检查填写内容');
    return;
  }

  // 显示加载状态
  const submitLoading = ElLoading.service({ text: '保存中...' });

  try {
    if (formData.caseId) {
      // 编辑操作
      await updateCaseStudy(formData);
      ElMessage.success('案例更新成功');
    } else {
      // 新增操作
      await addCaseStudy(formData);
      ElMessage.success('案例新增成功');
    }

    // 通知父组件保存成功，刷新列表
    emit('save');
    // 关闭弹窗
    handleClose();
  } catch (error) {
    ElMessage.error(`保存失败：${error.message || '未知错误'}`);
  } finally {
    // 关闭加载状态
    submitLoading.close();
  }
};
</script>

<style scoped>
.uploaded-img {
  position: relative;
  display: inline-block;
}

.delete-img-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  padding: 0;
  line-height: 20px;
  text-align: center;
}

.delete-img-btn:hover {
  background-color: rgba(255, 0, 0, 0.7);
  color: white;
}

.form-hint {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}
</style>
